<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Demand;
use Illuminate\Http\Request;
use App\Package\Attendance\Time;
use App\Package\Attendance\Days;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\Logic\Demand\StoreResource;

/**
 * 项目用人需求数据模型
 *
 * Date: 25/04/2018
 * @author George
 * @package App\Http\Controllers
 */
class DemandController extends Controller
{
	/**
	 * Date: 25/04/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(Request $request)
    {
		$month = $request->get('month');
		$project_id = $request->get('project_id');
		$query = Demand::query()->where('project_id', $project_id);

		// 根据开始和结束时间查询
		if ($month) {
			$query->whereBetween('date', [date("{$month}-01"), date("{$month}-t")]);
		}

		$days = $query->groupBy('date')->get();

    	return success($days);
    }

	/**
	 * 创建用人需求
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws Exception
	 */
    public function store(StoreResource $request)
    {
    	$project_id = $request->project_id;
    	$days = $request->demands;
    	$demands = [];
    	DB::beginTransaction();
		try {
			foreach ($days as $day) {
				foreach ($day['genres'] as $genre) {
					$attributes = [
						'date' => $day['date'],
						'project_id' => $project_id,
						'genre_id' => $genre['id'],
						'staff' => $genre['staff'],
						'created_at' => date('Y-m-d H:i:s'),
						'updated_at' => date('Y-m-d H:i:s')
					];
					$demands[] = Demand::create($attributes);
				}
			}
			DB::commit();
			return stored($demands);
		} catch (Exception $exception) {
			DB::rollBack();
			return failed('创建记录失败，可能是数据重复');
		}
    }

	/**
	 * 创建和更新
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws Exception
	 */
	public function modify(Request $request)
	{
		$this->validate($request, [
			'project_id' => 'required',
			'days' => 'required|array'
		]);

		$days = $request->get('days');
		$project_id = $request->get('project_id');

		$result = [];
		if (count($days) > 0) {
			DB::beginTransaction();
			try {
				foreach ($days as $day) {
					if (count($day['genres']) > 0) {
						foreach ($day['genres'] as $genre) {
							$attributes = [
								'date' => $day['date'],
								'project_id' => $project_id,
								'genre_id' => $genre['id']
							];
							if ($genre['staff'] > 0) {
								$result[] = Demand::query()->where([
									['project_id', '=', $project_id],
									['date', '=', $day['date']]
								])->updateOrCreate($attributes, ['staff' => $genre['staff']]);
							}
						}
					} else {
						// 删除用人需求
						DB::table('demands')->where('project_id', $project_id)
							->whereDate('date', $day['date'])->delete();
					}
				}
				DB::commit();
			} catch (Exception $exception) {
				DB::rollBack();
				return internalError('创建失败');
			}
		}

		return success($result);
    }

	/**
	 * 删除用人需求
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function destroy(Request $request)
	{
		$this->validate($request, [
			'project_id' => 'required',
			'date' => 'required'
		]);

		$date = $request->get('date');
		$project_id = $request->get('project_id');

		Demand::query()->where([
			['project_id', '=', $project_id],
			['date', '=', $date]
		])->delete();

		return deleted();
    }

	/**
	 * 获取单日的需求详情
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function day(Request $request)
	{
		$date = $request->get('date');
		$project_id = $request->get('project_id');

		$query = Demand::with(['genre' => function ($query) {
			/**
			 * @var Builder $query
			 */
			$query->select(['id', 'name']);
		}])->select(['id', 'date', 'genre_id', 'staff'])->where('project_id', $project_id);

		// 查询指定日期的数据
		$query->when($date, function ($query, $date) {
			/**
			 * @var Builder $query
			 */
			return $query->where('date', $date);
		});

		return success($query->get());
    }

	/**
	 * 获取项目的月用人需求列表
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function days(Request $request)
	{
		$month = $request->get('month');
		$label = $request->get('label', false);
		$project_id = $request->get('project_id');
		$query = Demand::query()->select(['id', 'date'])->where('project_id', $project_id);

		// 根据开始和结束时间查询
		if ($month) {
			$query->whereBetween('date', [date("{$month}-01"), date("{$month}-t")]);
		}

		$days = $query->orderBy('date')->groupBy('date')->get();
		// 判断是否需要生成Label
		if ($label) {
			$days = $days->map(function ($day) {
				$day->label = Days::toWeek($day->date);
				return $day;
			});
		}

		return success($days);
    }

	/**
	 * 按月计算总工时
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function times(Request $request)
	{
		$this->validate($request, [
			'month' => 'required',
			'project_id' => 'required'
		]);
		$month = $request->get('month');
		$project_id = $request->get('project_id');

		$start = date("{$month}-01");
		$end = date("{$month}-t");
		$demands = Demand::with('genre')
			->whereBetween('date', [$start, $end])
			->where('project_id', $project_id)->get();
		$times = 0;
		foreach ($demands as $demand) {
			$times += (Time::worktime($demand->date, $demand->genre->start, $demand->genre->end)) * $demand->staff;
		}
		return success(['times' => $times / 3600]);
    }
}
